import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestMysql {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://127.0.0.1:3306/java100?characterEncoding=utf-8&useSSL=true";
        String username = "root";
        String password = "1234";
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL(url);
        ((MysqlDataSource) dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setPassword(password);
        //建立连接
        Connection connection = dataSource.getConnection();
        //访问数据库
        String sql = "select * from book";
        PreparedStatement statement = connection.prepareStatement(sql);
        //执行sql
        ResultSet resultSet = statement.executeQuery();
        //遍历结果集
        while(resultSet.next()){
            System.out.println(resultSet.getString("name"));
            System.out.println(resultSet.getInt("price"));
        }
        //关闭连接，释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }

}
